import os
import sys
import pytest

# Make 'cqlib' importable even if you run tests directly from this folder.
# If you've installed cqlib into the environment, you can remove this section.
TESTS_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
CQLIB_SRC_HINTS = [
    os.path.abspath(os.path.join(TESTS_ROOT, "..", "..", "cqlib")),            # repo-root/cqlib
    os.path.abspath(os.path.join(TESTS_ROOT, "..", "..", "src")),              # repo-root/src
]
for hint in CQLIB_SRC_HINTS:
    if os.path.isdir(hint) and hint not in sys.path:
        sys.path.insert(0, hint)

# Matplotlib in headless mode for deterministic CI runs
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt


@pytest.fixture(autouse=True, scope="session")
def _matplotlib_rc():
    # Try to reduce cross-platform pixel drift.
    import matplotlib as mpl
    mpl.rcParams.update({
        "figure.dpi": 100,
        "savefig.dpi": 100,
        "font.size": 10,
        "axes.titlesize": 10,
        "axes.labelsize": 10,
        "xtick.labelsize": 8,
        "ytick.labelsize": 8,
        "legend.fontsize": 8,
        "text.kerning_factor": 0,
    })
    yield
    plt.close("all")


@pytest.fixture(scope="session")
def results_dir(tmp_path_factory):
    path = os.path.abspath(os.path.join(os.path.dirname(__file__), "mpl"))
    os.makedirs(path, exist_ok=True)
    return path


@pytest.fixture(scope="session")
def references_dir():
    path = os.path.abspath(os.path.join(os.path.dirname(__file__), "mpl", "references"))
    os.makedirs(path, exist_ok=True)
    return path

@pytest.fixture(scope="session")
def visual_threshold():
    # You can relax to 0.98–0.995 if fonts/antialiasing differ slightly across environments.
    return float(os.environ.get("CQLIB_VISUAL_THRESHOLD", "0.995"))
